package com.lianxi.Courses.controller;

import com.github.pagehelper.PageInfo;
import com.lianxi.Courses.constant.ResponseCodeConstant;
import com.lianxi.Courses.entity.*;
import com.lianxi.Courses.exception.CourseTypeExistException;
import com.lianxi.Courses.exception.RequestParameterErrorException;
import com.lianxi.Courses.service.ChapterService;
import com.lianxi.Courses.service.CourseService;
import com.lianxi.Courses.service.CourseTypeService;
import com.lianxi.Courses.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/type")
public class CourseTypeController {
    @Autowired
    private CourseTypeService typeService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private ChapterService chapterService;




    @RequestMapping("/findAll")
    public ModelAndView findAll(String pageNo, String pageSize, String parentId, String showCourses) throws RequestParameterErrorException {
        ModelAndView mav = new ModelAndView();
        if ("true".equals(showCourses) && parentId != null) {
            try {
                List<Course> courses = courseService.findByCourseTypeId(parentId);
                mav.addObject("courses", courses);
            } catch (RequestParameterErrorException e) {
                e.printStackTrace();
                mav.addObject("errorMessage", "查询课程列表失败，请稍后重试");
            }
        } else {
            PageInfo<CourseType> typePage = typeService.findPageByParentId(pageNo, pageSize, parentId);
            mav.addObject("typePage", typePage);
        }
        mav.addObject("selectedCourseTypeId", parentId);
        mav.setViewName("backend/back_courseTypeSet");
        return mav;
    }


    @RequestMapping("/addType")
    @ResponseBody
    public ResponseResult addType(String name, Integer parentId) {
        ResponseResult result = new ResponseResult();

        try {
            typeService.addCourseType(name, parentId);
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        } catch (CourseTypeExistException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        } catch (Exception e) {
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }

        return result;
    }

    @RequestMapping("/findById")
    @ResponseBody
    public ResponseResult findById(String id) {
        ResponseResult result = new ResponseResult();

        try {
            CourseType type = typeService.findById(id);
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
            result.setReturnObject(type);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        } catch (Exception e) {
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        return result;
    }

    @RequestMapping("/modifyType")
    @ResponseBody
    public ResponseResult modifyType(String id, String name) {
        ResponseResult result = new ResponseResult();
        try {
            typeService.modifyName(id, name);
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        } catch (CourseTypeExistException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        } catch (Exception e) {
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        return result;
    }

    @RequestMapping("/modifyStatus")
    @ResponseBody
    public ResponseResult modifyStatus(String id, String status) {
        ResponseResult result = new ResponseResult();
        try {
            typeService.modifyStatus(id, status);
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        } catch (Exception e) {
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        return result;
    }

    // 查询子类别
//    @RequestMapping("/findByCourseTypeId")
//    @ResponseBody
//    public ResponseResult findByCourseTypeId(String courseTypeId) {
//        ResponseResult result = new ResponseResult();
//        try {
//            List<Course> courses = courseService.findByCourseTypeId(courseTypeId);
//            result.setMessage("成功");
//            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
//            result.setReturnObject(courses);
//        } catch (RequestParameterErrorException e) {
//            result.setMessage(e.getMessage());
//            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
//        } catch (Exception e) {
//            result.setMessage("服务器内部异常");
//            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
//        }
//        return result;
//    }



    @RequestMapping("/findByCourseTypeId")
    @ResponseBody
    public ResponseResult findByCourseTypeId(String courseTypeId) {
        ResponseResult result = new ResponseResult();
        try {
            List<CourseType> subTypes = typeService.findByParentId(Integer.parseInt(courseTypeId));
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
            result.setReturnObject(subTypes);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        } catch (Exception e) {
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        return result;
    }












    @RequestMapping("/findByCourseId2")
    @ResponseBody
    public ResponseResult findByCourseId(Integer courseId) {
        ResponseResult result = new ResponseResult();
        try {
            List<Chapter> chapters = chapterService.findByCourseId(courseId);
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
            result.setReturnObject(chapters);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        } catch (Exception e) {
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        return result;
    }




    @RequestMapping("/findTopLevelTypes")
    @ResponseBody
    public ResponseResult findTopLevelTypes() {
        ResponseResult result = new ResponseResult();
        try {
            List<CourseType> topLevelTypes = typeService.findTopLevelTypes();
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
            result.setReturnObject(topLevelTypes);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        return result;
    }


    @RequestMapping({"/toFrontIndex", "/showIndex"})
    public ModelAndView toFrontIndex() {
        ModelAndView mav = new ModelAndView();
        try {
            List<CourseType> topLevelTypes = typeService.findTopLevelTypes();
            mav.addObject("topLevelTypes", topLevelTypes);
            mav.setViewName("backend/front_index");
        } catch (Exception e) {
            e.printStackTrace();
            mav.addObject("UserMsg", "服务器内部异常");
            mav.setViewName("backend/front_index");
        }
        return mav;
    }



    /**
     * 根据分类ID获取课程列表
     */
    @RequestMapping("/findCoursesByTypeId")
    @ResponseBody
    public ResponseResult findCoursesByTypeId(String courseTypeId) {
        ResponseResult result = new ResponseResult();
        try {
            List<Course> courses = courseService.findByTypeId(courseTypeId);
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
            result.setReturnObject(courses);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        } catch (Exception e) {
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        return result;
    }



    @RequestMapping("/toSearch")
    public ModelAndView toSearch(String keyword) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/backend/front_select");
        mav.addObject("Keyword", keyword);
        return mav;
    }






    @RequestMapping("/filterCourses")
    public ModelAndView filterCourses(@RequestParam(required = false) String firstLevelTypeId,
                                      @RequestParam(required = false) String thirdLevelTypeId,
                                      @RequestParam(required = false) String pageNo,
                                      @RequestParam(required = false) String pageSize,
                                      @RequestParam(required = false, defaultValue = "create_date DESC") String sortType) {
        ModelAndView mav = new ModelAndView();
        try {
            // 获取所有一级分类
            List<CourseType> firstLevelTypes = typeService.findTopLevelTypes();
            mav.addObject("firstLevelTypes", firstLevelTypes);

            // 如果选择了一级分类，获取其下的所有三级分类
            if (firstLevelTypeId != null && !firstLevelTypeId.isEmpty()) {
                List<CourseType> secondLevelTypes = typeService.findByParentId(Integer.parseInt(firstLevelTypeId));
                List<CourseType> thirdLevelTypes = new ArrayList<>();

                // 获取所有三级分类
                for (CourseType secondLevel : secondLevelTypes) {
                    List<CourseType> thirdLevels = typeService.findByParentId(secondLevel.getId());
                    thirdLevelTypes.addAll(thirdLevels);
                }

                mav.addObject("thirdLevelTypes", thirdLevelTypes);
                mav.addObject("selectedFirstLevelId", firstLevelTypeId);
                mav.addObject("selectedThirdLevelId", thirdLevelTypeId);
            }

            // 创建查询参数
            CourseExample example = new CourseExample();
            example.setOrderByClause(sortType);
            CourseExample.Criteria criteria = example.createCriteria();

            // 如果选择了三级分类，设置分类ID
            if (thirdLevelTypeId != null && !thirdLevelTypeId.isEmpty()) {
                criteria.andCourseTypeIdEqualTo(Integer.parseInt(thirdLevelTypeId));
            }
            // 如果只选择了一级分类，需要通过三级分类间接查询
            else if (firstLevelTypeId != null && !firstLevelTypeId.isEmpty()) {
                // 获取一级分类下的所有三级分类ID
                List<CourseType> secondLevelTypes = typeService.findByParentId(Integer.parseInt(firstLevelTypeId));
                List<Integer> thirdLevelTypeIds = new ArrayList<>();

                for (CourseType secondLevel : secondLevelTypes) {
                    List<CourseType> thirdLevels = typeService.findByParentId(secondLevel.getId());
                    for (CourseType thirdLevel : thirdLevels) {
                        thirdLevelTypeIds.add(thirdLevel.getId());
                    }
                }

                if (!thirdLevelTypeIds.isEmpty()) {
                    criteria.andCourseTypeIdIn(thirdLevelTypeIds);
                }
            }

            // 查询课程并分页
            PageInfo<Course> coursePage = courseService.findPageByExample(example, pageNo, pageSize);
            mav.addObject("coursePage", coursePage);

        } catch (Exception e) {
            e.printStackTrace();
            mav.addObject("errorMessage", "查询课程失败，请稍后重试");
        }

        mav.setViewName("backend/front_select");
        return mav;
    }



































}
